﻿

using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;

namespace LinqBll
{
    public class ObjectContextBaseCore<T> : IObjectSetCore<T>
        where T : class,new()
    {
        #region Members
        System.Data.Objects.ObjectContext Context { get; set; }

        public ObjectContextBaseCore(ObjectContext context)
        {
            if (context != null)
                Context = context;
            throw new ArgumentNullException();
        }

        #endregion


        public System.Data.Objects.ObjectSet<T> ObjectSet
        {
            get { return this.Context.CreateObjectSet<T>(); }
        }

        public void CreateList(IEnumerable<T> ts)
        {
            foreach (var i in ts)
                this.Create(i);
        }

        public void Create(T t)
        {
            this.Attach(t);
        }

        public void Delete(T t)
        {
            dynamic temp = t;
            temp.Flag = false;
        }

        public void Update(T t)
        {
            this.Attach(t);
        }

        public System.Collections.Generic.IList<T> Select(int start, int limit)
        {
            return this.ObjectSet.Skip(start).Take(limit).ToList();
        }

        public void SaveChanges()
        {
            this.Context.SaveChanges();
        }

        public void Dispose()
        {
            this.Context.Dispose();
        }

        protected void Attach(T t)
        {
            this.ObjectSet.Attach(t);
            this.Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, t);
        }


        public void Delete(IEnumerable<T> ts)
        {
            foreach (var i in ts)
                Delete(i);
        }

        public void Update(IEnumerable<T> ts)
        {
            foreach (var i in ts)
                Update(i);
        }

        public T Query(Func<T, bool> func)
        {
            return ObjectSet.FirstOrDefault(func);
        }


        public IQueryable<T> QueryList(Func<T, bool> func)
        {
            throw new NotImplementedException();
        }

        public IQueryable<T> QueryList(Func<T, int, bool> func)
        {
            throw new NotImplementedException();
        }


        public IQueryable<T> QueryList()
        {
            throw new NotImplementedException();
        }
    }
}
